<template>
  <Card
    title="查看邮件"
    v-loading="loading"
    :bordered="false"
    :head-style="{ padding: '0' }"
    :body-style="{ padding: '10px 0' }"
  >
    <div class="flex flex-col gap-2">
      <div style="background-color: #e7eff6" class="flex justify-start gap-2 p-8px mb-2">
        <Button type="primary" @click="handleReturn">
          <template #icon>
            <RollbackOutlined />
          </template>
          返回
        </Button>
        <Button type="primary" @click="handleRefresh">
          <template #icon>
            <RedoOutlined />
          </template>
          刷新
        </Button>
        <Button type="primary" @click="handleReply">
          <template #icon>
            <Icon icon="clarity:chat-bubble-line" />
          </template>
          回复
        </Button>
        <Button @click="handleDelete">
          <template #icon> <DeleteOutlined style="color: red" /> </template>
          删除
        </Button>
        <Button type="primary" @click="handleTransmit">
          <template #icon> <SendOutlined /> </template>
          转发
        </Button>
      </div>
      <div
        class="flex flex-col gap-2 p-2"
        style="background-color: #efefef; border-bottom: 1px solid #acdcdc"
      >
        <div class="flex gap-2">
          <div>发件人：</div>
          <div>{{ model.sender }}</div>
        </div>
        <div class="flex gap-2">
          <div>收件人：</div>
          <div>{{ model.receiver }}</div>
        </div>
        <div class="flex gap-2">
          <div>时间：</div>
          <div>{{ model.sendTime }}</div>
        </div>
        <div class="flex gap-2">
          <div>主题：</div>
          <div>{{ model.subject }}</div>
        </div>
        <div class="flex gap-2" v-if="model.cc">
          <div>抄送：</div>
          <div>{{ model.cc }}</div>
        </div>
      </div>
      <div class="flex flex-col gap-2 p-2">
        <div>
          <div v-if="model.content" v-html="model.content"></div>
          <div class="mt-5" v-if="model.attachments && model.attachments.length">
            <div v-for="(item, index) in model.attachments" :key="index">
              <a @click="handleDonwload(item)">{{ item.name }}</a>
              <a @click="handlePreview(item)" title="预览" v-if="item.previewUrl" class="ml-3"
                ><EyeOutlined style="color: rgba(28, 106, 235, 1)"
              /></a>
            </div>
          </div>
        </div>
      </div>
      <!-- <template v-if="isShowEditInfo">
        <div>
          <Tinymce :showImageUpload="false" v-model="dataRef.content" />
        </div>
        <div>
          附件：<Upload :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove">
            <Button>
              <upload-outlined />
              上传文件
            </Button>
          </Upload>
        </div>
        <div class="text-center">
          <Button type="primary" @click="handleSubmit">回复</Button>
        </div>
      </template> -->
    </div>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, onMounted, computed, nextTick, h, inject } from 'vue';
  import { Card, Checkbox, Upload, UploadProps, Button } from 'ant-design-vue';
  // import { Tinymce } from '/@/components/Tinymce/index';
  import {
    RedoOutlined,
    DeleteOutlined,
    SendOutlined,
    RollbackOutlined,
    // UploadOutlined,
    EyeOutlined,
  } from '@ant-design/icons-vue';
  import Icon from '/@/components/Icon';
  import {
    getEmailShowMail,
    // getEmailReply,
    getEmailDelMail,
    getEmailSendReceipt,
  } from '/@/api/email/externalEmail';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dateUtil as dayjs } from '/@/utils/dateUtil';

  const props = defineProps({
    type: {
      type: String,
      default: '',
    },
    currentRecord: {
      type: Object,
      default: () => {
        return {};
      },
    },
    isDraft: {
      type: Boolean,
      default: false,
    },
  });
  const emit = defineEmits(['handle-return', 'handle-transmit', 'handle-reply']);
  const { createMessage, createConfirm } = useMessage();
  // const userInfo = userStore.getUserInfo;
  const loading = ref(false);
  // const isShowEditInfo = computed(() => props.type != 'garbageBinbox');
  const internalEmail = inject('internalEmail') as any;
  // const dataRef = ref({
  //   content: '',
  // });
  const model = ref<Recordable>({});
  //返回
  const handleReturn = () => {
    emit('handle-return');
  };
  //刷新
  const handleRefresh = () => {
    fetch();
    // handleClear();
  };
  //回复
  const handleReply = () => {
    emit('handle-reply', model.value);
  };
  //删除
  const handleDelete = async () => {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '确定删除吗？'),
      onOk: async () => {
        try {
          loading.value = true;
          await getEmailDelMail({
            emailId: internalEmail.emailInfo.value.id,
            ids: props.currentRecord.id,
          });
          createMessage.success('操作成功');
          loading.value = false;
          // handleRefresh();
          handleReturn();
        } catch (error) {
        } finally {
          loading.value = false;
        }
      },
    });
  };
  //转发
  const handleTransmit = () => {
    emit('handle-transmit', model.value);
  };

  //回执
  const handleReceiptState = () => {
    createConfirm({
      iconType: 'info',
      title: () => h('span', '消息发送者需要回执，现在就发送回执么？'),
      onOk: async () => {
        try {
          loading.value = true;
          await getEmailSendReceipt(model.value);
          // handleRefresh();
          createMessage.success('操作成功');
        } catch (error) {
          console.log(error);
        } finally {
          loading.value = false;
        }
      },
    });
  };

  // const fileList = ref<UploadProps['fileList']>([]);
  // const handleRemove: UploadProps['onRemove'] = (file) => {
  //   const index = fileList.value.indexOf(file);
  //   const newFileList = fileList.value.slice();
  //   newFileList.splice(index, 1);
  //   fileList.value = newFileList;
  // };
  // const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  //   fileList.value = [...fileList.value, file];
  //   return false;
  // };

  //确定
  // const handleSubmit = async () => {
  //   try {
  //     console.log('dataRef', dataRef.value);
  //     console.log('props.currentRecord', props.currentRecord);
  //     if (!dataRef.value.content) {
  //       createMessage.warning('请输入内容');
  //       return;
  //     }
  //     const params = {
  //       title: props.currentRecord.title,
  //       id: props.currentRecord.id,
  //       to: props.currentRecord.sender,
  //       userRealName: props.currentRecord.senderRealName,
  //       att1: '',
  //       content: dataRef.value.content,
  //     };
  //     console.log('params', params);
  //     const url = `?emailId=${internalEmail.emailInfo.value.id}`;

  //     fileList.value?.forEach((item, index) => {
  //       params[`att${index + 1}`] = item;
  //     });
  //     const formata = new FormData();
  //     for (let v in params) {
  //       formata.append(v, params[v]);
  //     }
  //     loading.value = true;
  //     await getEmailReply(formata,url);
  //     loading.value = false;
  //     handleRefresh();
  //   } catch (error) {
  //   } finally {
  //     loading.value = false;
  //   }
  // };

  // const handleClear = () => {
  //   dataRef.value.content = '';
  //   fileList.value = [];
  // };

  const userStore = useUserStore();
  const serverInfo = userStore.getServerInfo;
  //下载
  const handleDonwload = (record) => {
    const path = record.visualPath + '/' + record.diskName;
    const fileName = record.name;
    const url = path
      ? serverInfo.rootPath + (path && path.startsWith('/') ? path : `/${path}`)
      : '';
    downloadByUrl({ url, fileName });
  };

  const handlePreview = computed(() => (record: any) => {
    const rootPath = serverInfo.rootPath;
    window.open(rootPath + '/' + record.previewUrl);
  });

  const fetch = () => {
    nextTick(async () => {
      if (!props.currentRecord.id) return;
      loading.value = true;
      const res = await getEmailShowMail({
        emailId: internalEmail.emailInfo.value.id,
        id: props.currentRecord.id,
      });
      model.value = res;
      if (model.value.sendTime) {
        model.value.sendTime = dayjs(model.value.sendTime).format('YYYY-MM-DD hh:mm:ss');
      }
      // dataRef.value.content =
      //   `<br><br><br><br><br><br><br><p>------------------转发邮件信息------------------</p>` +
      //   model.value.content;
      loading.value = false;
      //根据条件判断回执
      if (res.receiptState == 1) {
        handleReceiptState();
      }
    });
  };
  onMounted(fetch);
</script>
<style lang="less" scoped>
  .session-list-content {
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
    position: relative;
    padding: 8px;
    background-color: #f3f3f3;
    border: 1px solid #92c64a;
    word-wrap: break-word;
    line-height: 25px;
    border: 1px solid #d5d5d5;
  }
  :deep(.ant-card-head-title) {
    padding: 8px 8px 0;
  }
</style>
